package com.cooper.controllers.seller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.AppConstants;
import com.cooper.constants.DictConstants;
import com.cooper.constants.ResourceConstants;
import com.cooper.controllers.Controller;
import com.cooper.controllers.LoginRequired;
import com.cooper.core.JsonResult;
import com.cooper.entity.ItemInfo;
import com.cooper.entity.UserInfo;
import com.cooper.helper.ItemExtendHelper;
import com.cooper.pagination.PageInfo;
import com.cooper.pagination.PageResult;
import com.cooper.service.admin.AddressService;
import com.cooper.service.admin.LocationService;
import com.cooper.service.admin.MallCategoryService;
import com.cooper.service.admin.SavedService;
import com.cooper.service.core.DictService;
import com.cooper.service.item.ItemImageService;
import com.cooper.service.item.ItemRepository;
import com.cooper.service.item.ItemSkuService;
import com.cooper.util.Controllers;
import com.cooper.vo.AddressVo;
import com.cooper.vo.ItemInfoVo;
import com.cooper.vo.ItemSearchVo;
import com.cooper.vo.LocationVo;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

@LoginRequired
public class ProductController extends Controller{
	
	@Autowired
	private MallCategoryService mallCategoryService;
	
	@Autowired
	private LocationService locationService;
	
	@Autowired
	private ItemRepository itemRepository;
	
	@Autowired
	private AddressService addressService;
	
	@Autowired
	private ItemImageService itemImageService;
	
	@Autowired
	private ItemSkuService itemSkuService;
	
	@Autowired
	private SavedService savedService;
	
	@Autowired
	private DictService dictService;
	
	@Get("list")
	@Post("list")
	public String execute(Invocation inv, PageInfo pageInfo, ItemSearchVo searchVo) throws Exception{
		Long userId = Controllers.getUserId(inv);
		pageInfo.setPageSize(ITEMS_PER_PAGE);
		PageResult<ItemInfoVo> pageResult = this.itemRepository.queryForList(userId, searchVo, pageInfo);
		inv.addModel("entryList", pageResult.getResult());
		inv.addModel(AppConstants.pageInfo, pageInfo);
		return "ProductList";
	}
	
	@Get("edit")
	public String edit(Invocation inv, @Param("id") long itemId) throws Exception{
		UserInfo userInfo = Controllers.getUserInfo(inv);
		
		List<LocationVo> firstLevelLocationList = this.locationService.getAllLocationWithChilds(LANG);
		inv.addModel("firstLevelLocationList", firstLevelLocationList);
		
		inv.addModel("deletedMap", this.dictService.makeOptionList(DictConstants.DELETED, "", ""));
		
		String productDesc = this.savedService.doGet(ResourceConstants.SavedResName.PRODUCT_DESC, 
				0 == itemId?"USER_"+userInfo.getId():"ITEM_" + itemId);
		String logisticsDesc = this.savedService.doGet(ResourceConstants.SavedResName.LOGISTICS_DESC, 
				0 == itemId?"USER_"+userInfo.getId():"ITEM_" + itemId);
		
		ItemInfo itemInfo = null;
		if(0 < itemId){
			itemInfo = this.itemRepository.loadById(itemId);
			if(null != itemInfo && userInfo.getId().equals(itemInfo.getSellerId())){
				inv.addModel("categoryName", this.mallCategoryService.findName(itemInfo.getCid()));
				inv.addModel("itemImages", this.itemImageService.getItemImageListByItemId(itemId));
				inv.addModel("itemSkuList", this.itemSkuService.getItemSkuListByItemId(itemId));
				
				AddressVo originAddress = this.addressService.getAddressVoByOriginAndOuterId(ResourceConstants.AddressOrigin.ITEM_ORIGIN, itemId);
				inv.addModel("originAddress", originAddress);
				
				if(StringUtils.isBlank(productDesc)){
					productDesc = itemInfo.getProductDesc();
				}
				if(StringUtils.isBlank(logisticsDesc)){
					logisticsDesc = itemInfo.getLogisticsDesc();
				}
			}
		}
		
		if(null == itemInfo){
			itemInfo = new ItemInfo();
		}
		inv.addModel("itemInfo", itemInfo);
		inv.addModel("productDesc", productDesc);
		inv.addModel("logisticsDesc", logisticsDesc);
		return "ProductEdit";
	}
	
	@Post("save")
	public Object save(Invocation inv, ItemInfo itemInfo, ItemExtendHelper helper) {
		JsonResult json = new JsonResult();
		UserInfo userInfo = Controllers.getUserInfo(inv);
		if(StringUtils.isBlank(helper.getOriginIds()) || StringUtils.isBlank(helper.getOriginNames())){
			json.setMessage("ORIGIN REQUIRED");
		} else if(StringUtils.isBlank(helper.getStrImageArray())){
			json.setMessage("ITEM IMAGE REQUIRED");
		} else if(StringUtils.isBlank(helper.getStrSkuArray())){
			json.setMessage("ITEM STOCK REQUIRED");
		} else {
			try{
				long itemId = (null == itemInfo.getId()?0:itemInfo.getId());//不允许改变
				json = this.itemRepository.saveItem(userInfo, itemInfo, helper);
				//保存成功，则清除暂存信息
				this.savedService.doSave(ResourceConstants.SavedResName.PRODUCT_DESC, 
						0 == itemId?"USER_"+userInfo.getId():"ITEM_" + itemId, "");
				this.savedService.doSave(ResourceConstants.SavedResName.LOGISTICS_DESC, 
						0 == itemId?"USER_"+userInfo.getId():"ITEM_" + itemId, "");
			} catch(Exception e){
				json.setMessage(e.getMessage());
				e.printStackTrace();
			}
		}
		return json;
	}
	
	@Post("delete")
	public Object delete(Invocation inv, @Param("id") long itemId) throws Exception{
		JsonResult json = new JsonResult();
		UserInfo userInfo = Controllers.getUserInfo(inv);
		ItemInfo itemInfo = this.itemRepository.loadById(itemId);
		if(null == itemInfo || StringUtils.isEmpty(itemInfo.getTitle())){
			json.setMessage("PRODUCT ITEM NOT EXISTS!");
		} else if(!userInfo.getId().equals(itemInfo.getSellerId())){
			json.setMessage("YOU DON'T HAVE PERMISSION TO DELETE THIS PRODUCT ITEM!");
		} else {
			Controllers.prepareEntityForDataSaving(itemInfo, userInfo, true);
			this.itemRepository.deleteEntity(itemInfo);
			json.setSuccess(true);
			json.setMessage("DELETE ITEM {0} SUCCESSFUL!", itemInfo.getTitle());
		}
		return json;
	}
	
}
